package me.firstapp.spi.base.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusObject;
import me.firstapp.common.utils.ShaSign;
import me.firstapp.spi.base.BaseService;

@Service
public class BaseServiceImpl implements BaseService {
	protected Logger logger = LoggerFactory.getLogger(BaseServiceImpl.class);

	@Value("#{configProperties['api.server.url']}")
	protected String apiUrl;
	@Value("#{configProperties['api.server.key']}")
	protected String apiKey;
	@Value("#{configProperties['api.server.secret']}")
	protected String apiSecret;

	@Autowired
	protected RestTemplate restTemplate;

	protected JSONObject api(Map<String, Object> parameters, String uri, HttpMethod method, String apiName) {
		Calendar calendar = Calendar.getInstance();
		ShaSign shaSign = ShaSign.getSign(apiKey, apiSecret, calendar.getTime());
		StringBuilder url = new StringBuilder(apiUrl);
		url.append(uri);

		url.append("?apiKey=").append(apiKey);
		url.append("&timestamp=").append(calendar.getTimeInMillis());

		if (parameters != null) {
			for (String key : parameters.keySet()) {
				url.append("&").append(key).append("=").append(parameters.get(key) == null ? "" : parameters.get(key));
				shaSign.addParam(key, parameters.get(key));
			}
		}
		url.append("&sign=").append(shaSign.signParams());
		JSONObject resultJson = null;
		try {
			logger.info("调用[" + apiName + "]api开始");
			ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), method, null, String.class);
			logger.info("调用[" + apiName + "]api结束，返回结果为:" + responseEntity.getBody());
			resultJson = JSONObject.parseObject(responseEntity.getBody());
		} catch (RestClientException e) {
			throw new ServiceException(new StatusObject("error", "访问API接口异常"));
		}
		return resultJson;
	}
	
	protected JSONObject apiBody(Map<String, Object> parameters, String uri, String apiName, Map<String, Object> searchParams){
		Calendar calendar = Calendar.getInstance();
		ShaSign shaSign = ShaSign.getSign(apiKey, apiSecret, calendar.getTime());
		StringBuilder url = new StringBuilder(apiUrl);
		url.append(uri);
		
		url.append("?apiKey=").append(apiKey);
		url.append("&timestamp=").append(calendar.getTimeInMillis());
		
		if (parameters != null) {
			for (String key : parameters.keySet()) {
				url.append("&").append(key).append("=").append(parameters.get(key) == null ? "" : parameters.get(key));
				shaSign.addParam(key, parameters.get(key));
			}
		}
		url.append("&sign=").append(shaSign.signParams());
		
		if (searchParams == null) {
			searchParams = new HashMap<>();
		}
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
		HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(searchParams), headers);
		
		JSONObject resultJson = null;
		try {
			logger.info("调用[" + apiName + "]api开始");
			ResponseEntity<String> responseEntity = restTemplate.exchange(url.toString(), HttpMethod.POST, formEntity,
					String.class);
			logger.info("调用[" + apiName + "]api结束，返回结果为:" + responseEntity.getBody());
			resultJson = JSONObject.parseObject(responseEntity.getBody());
		} catch (RestClientException e) {
			throw new ServiceException(new StatusObject("error", "访问API接口异常"));
		}
		return resultJson;
	}
}
